/*
MIT License

Copyright (c) 2009 NewsGator Technologies Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/


var NGCheckbox = function(checkConfigArray, parentBuzzObj, cbOpts) {
	//private properties
	var checkedFeedAry = [];
	var slaveCache = {};
	var pageName = cbOpts.pageName || document.location.href.substring(document.location.href.lastIndexOf("/") + 1);

	//public properties
	this.parentBuzz = parentBuzzObj;
	this.checkConfigs = checkConfigArray;

	this.widgetContainerId = cbOpts.contentContainerId || "buzzContainer";
	this.childTemplate = cbOpts.childTemplate || "childTemplate";
	this.checkboxContainers = cbOpts.checkboxContainers || ["checkboxContainer"];
	this.defaultCheckCount = cbOpts.defaultCheckCount || 2;
	this.checkboxIdPrefix = cbOpts.checkboxIdPrefix || "ngCheckbox";

	//EVENT HOOKS============
	var events = {
	//preInitializeEvents
	//postInitializeEvents
	//preCreateCheckboxesEvents
	//postCreateCheckboxesEvents
	//preRenderBuzzEvents
	//postRenderBuzzEvents
	//postDeselectAllTabsEvents
	//postHighlightTabEvents
	//displayLoadingFailedEvents
	//loadingTemplateNotSpecifiedEvents
	//noConfigFoundEvents
};
//END EVENT HOOKS========

//private
var _this = this;

this.initialize = function() {
	executeEvents("preInitialize");

	_this.readCookie();

	if (checkConfigArray != null) {
		_this.createCheckboxes();
	}
	executeEvents("postInitialize");
};

this.createCheckboxes = function() {
	executeEvents("preCreateCheckboxes");

	var maxPerCol = Math.round((_this.checkConfigs.length / _this.checkboxContainers.length));
	var count = 0;
	var containerIndex = 0;
	var cbxContainer = document.getElementById(_this.checkboxContainers[containerIndex]);
	if (cbxContainer == null) {
		_this.debug("unable to find checkbox container");
		return;
	}

	var hasCookie = checkedFeedAry.hasFeeds;

	for (x = 0; x < _this.checkConfigs.length; x++) {
		var checkConfig = _this.checkConfigs[x];

		count++;
		if (count > maxPerCol) {
			containerIndex++;
			var cbxContainer2 = document.getElementById(_this.checkboxContainers[containerIndex]);
			if (cbxContainer2 != null) {
				cbxContainer = cbxContainer2;
				cbxContainer.innerHTML = "";
			}
			count = 0;
		}

		var li = document.createElement("div");
		li.style.listStyleType = "none";


		var cbx = document.createElement("input");
		cbx.type = "checkbox";
		cbx.style.marginLeft = "0px";
		cbx.id = _this.checkboxIdPrefix + "_" + _this.parentBuzz.buzzId + "_" + checkConfig.buzzId;

		//set the checkboxId back to the config object so that we can find it easily
		checkConfig.checkboxId = cbx.id;
		cbx.onclick = _this.checkboxClick;

		li.appendChild(cbx);

		var label = document.createElement("label");
		label.innerHTML = checkConfig.name;
		label.setAttribute("for", cbx.id);
		li.appendChild(label);

		cbxContainer.appendChild(li);

		//NOTE: checking the checkbox MUST be done AFTER the element
		//is added to the page or else IE won't check the box!
		if (
					(!hasCookie && (x < _this.defaultCheckCount || checkConfig.defaultChecked)) ||
					(hasCookie && checkedFeedAry[checkConfig.checkboxId])
				) {
			cbx.checked = "true";
			checkedFeedAry[checkConfig.checkboxId] = true;
			_this.addFeed(checkConfig);
		}

		_this.debug("checkbox " + _this.checkConfigs[x].buzzId);
	}

	executeEvents("postCreateCheckboxes");
};


this.findCheckConfigByCheckboxId = function(checkboxId) {
	for (var x = 0; x < _this.checkConfigs.length; x++) {
		if (checkboxId == _this.checkConfigs[x].checkboxId) {
			return _this.checkConfigs[x];
		}
	}

	_this.debug("unable to find a checkConfig with checkboxId of '" + checkboxId + "'");
	return null;
};

this.checkboxClick = function(evt) {
	evt = evt || window.event;
	var obj = evt.target || evt.srcElement;

	var configItem = _this.findCheckConfigByCheckboxId(obj.id);
	if (configItem == null) {
		return;
	}

	_this.onCheckChange(configItem, obj.checked);
};

this.onCheckChange = function(checkConfig, checked) {
	try {
		if (checked) {
			_this.addFeed(checkConfig);
		}
		else {
			_this.removeFeed(checkConfig);
		}
	}
	catch (ex) { _this.debug(ex.message); }
};

this.addFeed = function(checkConfig) {
	_this.renderBuzz(checkConfig);

	checkedFeedAry[checkConfig.checkboxId] = true;
	checkedFeedAry.hasFeeds = true;

	executeEvents("postFeedAdded", [checkConfig]);
	_this.writeCookie();
};


this.renderBuzz = function(checkConfig) {
	//There is some sort of problem going on in here.  don't have time at the moment to figure it out :-(
	try {
		var subTgt = document.createElement("div");
		subTgt.id = "subTgt_" + checkConfig.checkboxId;

		var tgt = document.getElementById(_this.widgetContainerId);

		if (tgt.firstChild) {
			tgt.insertBefore(subTgt, tgt.firstChild);
		}
		else {
			tgt.appendChild(subTgt);
		}

		var slave;
		if (slaveCache[checkConfig.buzzId]) {
			slave = slaveCache[checkConfig.buzzId];
		} else {

			//Make the extra args object by mixing together the parentBuzz's extraArgs with the checkConfig's extraArgs
			var eArgs = {};
			if (_this.parentBuzz._extraArgs) {
				for (var key in _this.parentBuzz._extraArgs) {
					eArgs[key] = _this.parentBuzz._extraArgs[key];
				}
			}

			if (checkConfig.extraArgs) {
				for (var key in checkConfig.extraArgs) {
					eArgs[key] = checkConfig.extraArgs[key];
				}
			}

			eArgs.DisplayName = checkConfig.name;
			eArgs.Category = checkConfig.name;
			eArgs.suppressScripts = true;
			eArgs.suppressStyles = true;
			eArgs.templateId = checkConfig.template || _this.childTemplate;

			//slave = slaveCache[checkConfig.buzzId] = this.parentBuzz.createSlaveWidget(checkConfig.buzzId, slaveArgs);
			this.parentBuzz.loadSubordinateWidget(checkConfig.buzzId, subTgt.id, eArgs, function(args) {
				var slave = args.buzzObj;
				slaveCache[checkConfig.buzzId] = slave;

				executeEvents("preRenderBuzz", [checkConfig, slave]);

				slave.render();

				executeEvents("postRenderBuzz", [checkConfig, slave]);
			});
		}
	} catch (ex) {
		_this.debug(ex.message);
	}
};

this.removeFeed = function(checkConfig) {
	//Remove DOM nodes from the UI
	var toRemove = "subTgt_" + checkConfig.checkboxId;

	removeElem = document.getElementById(toRemove);
	if (removeElem && removeElem.parentNode && removeElem.parentNode.removeChild) {
		removeElem.parentNode.removeChild(removeElem);
	}

	//Remove buzz from checked feeds & whatnot
	checkedFeedAry[checkConfig.checkboxId] = false;
	_this.writeCookie();

	executeEvents("postFeedRemoved", [checkConfig]);

};


this.readCookie = function() {
	var feed_cookie = _this.getCookie(pageName + "checkedFeeds");
	if (feed_cookie != null) {
		var feeds = feed_cookie.split(",");
		for (var i = 0; i < feeds.length; i++) {
			checkedFeedAry[feeds[i]] = true;
		}
		checkedFeedAry.hasFeeds = true;
	}
};

this.getCookie = function(sName) {
	var aCookie = document.cookie.split("; ");
	for (var i = 0; i < aCookie.length; i++) {
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0]) {
			return unescape(aCrumb[1]);
		}
	}
	return null;
};

this.writeCookie = function() {
	var feedIds = [];
	var blankObj = {};
	for (var key in checkedFeedAry) {
		if (checkedFeedAry[key] && typeof blankObj[key] == "undefined") {
			feedIds.push(key);
		}
	}

	var cookieVal = feedIds.join(",");
	var cookieName = pageName + "checkedFeeds";

	date = new Date();
	document.cookie = cookieName + "=" + escape(cookieVal) + "; expires=Mon, 1 May 2026 23:59:59 UTC";
};

var trim = function(s) {
	return s.replace(/^\s*(.*)\s*$/, "$1");
};

var getConfigIndexFromId = function(id) {
	if (id.lastIndexOf("_") != -1) {
		return id.subString(id.lastIndexOf("_") + 1);
	}
	return -1;
};


this.debug = function() {
	if (ng_debug) {
		return ng_debug;
	} else if (typeof console != "undefined") {
		return console.debug || console.log || console.warn || function() { };
	}
	return function() { };
} ();


this.removeEvents = function(eventName) {
	events[eventName] = null;
};

this.addEvent = function(eventName, action) {
	events[eventName] = events[eventName] || [];
	events[eventName].push(action);
};

//internal method
var executeEvents = function(eventName, arrEventArgs) {
	if (events[eventName]) {
		_this.debug("Executing event: " + eventName, arrEventArgs);
		var arrEvents = events[eventName];
		for (var i = 0; i < arrEvents.length; i++) {
			try {
				var func = arrEvents[i];
				func.apply(_this, arrEventArgs);
			} catch (e) {
			}
		}
	}
};
};

var NGCheckConfig = function(buzzId, name, extraArgs) {
	//Public constructor properties
	this.buzzId = buzzId;
	this.name = name;
	this.extraArgs = extraArgs || null;


	//Optional public properties
	this.checkboxId = "";
};

/* Some "static" methods on the checkbox class */

NGCheckbox.toggleBuzz = function(elem, toggleElemId, expandImg, collapseImg) {
	var toggle = document.getElementById(toggleElemId);
	if (toggle) {
		if (toggle.style.display == "none") {
			toggle.style.display = "block";
			elem.src = collapseImg;
		} else {
			toggle.style.display = "none";
			elem.src = expandImg;
		}
	}
};